<template>
  <div ref="barChart" :style="{ width: width, height: height }"></div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'ElectricityBarChart',
  props: {
    seriesName: {
      type: String,
      default: () => {
        return ''
      }
    },
    height: {
      type: String,
      default: () => '100%'
    },
    width: {
      type: String,
      default: () => '100%'
    },
    dataList: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    seriesName: {
      handler(v) {
        this.initChart();
      }
    },
    dataList: {
      handler(v) {
        this.electricityData = v;
        this.initChart();
      },
      deep: true
    }
  },
  data() {
    return {
      electricityData: [],
    };
  },
  mounted() {
    this.initChart();
  },
  methods: {
    listener(chartDom, myChart) {
      const resizeObserver = new ResizeObserver(() => {
        if (myChart) {
          myChart.resize();
        }
      });
      resizeObserver.observe(chartDom);
    },
    initChart() {
      const chartDom = this.$refs.barChart;
      const myChart = echarts.init(chartDom);

      const option = {
        title: {
          text: '',
        },
        tooltip: {
          trigger: 'axis',
        },
        grid: {
          left: '5%',
          right: '5%',
          top: '20%',
          bottom: '25%'
        },
        xAxis: {
          type: 'category',
          data: this.electricityData.map(item => item.time),
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            name: this.seriesName,
            type: 'bar', // 改为柱状图
            itemStyle: {
              color: '#3383FF' 
            },
            data: this.electricityData.map(item => item.value),
          },
        ],
        dataZoom: [
          {
            type: 'slider', // 会创建一个滑动条来选择区域
            start: 0, // 初始选中范围的开始百分比
            end: 100, // 初始选中范围的结束百分比
          },
          {
            type: 'inside', // 会使图表内的数据区域可以拖拽和缩放
            start: 0,
            end: 100,
          }
        ],
      };

      myChart.setOption(option);
      this.listener(chartDom, myChart);
    },
  }
};
</script>

<style scoped>
/* 样式 */
</style>